package com.vilicode.Utils;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;
public class MyCipher {
    public MyCipher() {
    }

    private static Key loadKey(String keyStr){
        Key key = null;
        try {
            KeyGenerator generator = KeyGenerator.getInstance("DES");
//            generator.init(new SecureRandom(keyStr.getBytes(StandardCharsets.UTF_8)));

            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(keyStr.getBytes());
            generator.init(secureRandom);

            key = generator.generateKey();
        }catch (Exception e){
            e.printStackTrace();
        }
        return key;
    }

    public static String encrypt(String keyStr,String content){
        try {
            Key key = loadKey(keyStr);
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE,key);
            byte[] source = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
            return new String(Base64.getEncoder().encode(source),StandardCharsets.UTF_8);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String decrypt(String keyStr,String content){
        try {
            Key key = loadKey(keyStr);
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE,key);
            byte[] source =Base64.getDecoder().decode(content.getBytes(StandardCharsets.UTF_8));
            return new String(cipher.doFinal(source),StandardCharsets.UTF_8);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

}
